# -*- coding: utf-8 -*-
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        # 1输入图像通道，6个输出通道，5×5平方卷积
        # 建立了两个卷积层，self.conv1, self.conv2
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        #三个全连接层
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 注意，2D卷积层的输入data维数是 batchsize*channel*height*width
        # max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If size is a square you can only specify a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))   #激活函数
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

    def num_flat_features(self, x):
        size = x.size()[1:]  # all dimensions except the batch dimension
        num_features = 1
        for s in size:
            num_features *= s
        return num_features

net = Net()
learning_rate = 0.01
parame = list(net.parameters())       #net.parameters()返回模型需要学习的参数
for f in parame:
    f.data.sub_(f.grad.data * learning_rate)
print(net)
# print(len(list(net.parameters())))
input = Variable(torch.randn(1,1,32,32))
out = net(input)
print(out)
net.zero_grad()
out.backward(torch.randn(1,10))